package com.gofaraway.service.student.leetcode;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;

/**
 * @author ChenPeng
 * @Date 2024/7/29 22:54
 */
public class Demo08 {


    /**
     * 最长连续序列
     * 给定一个未排序的整数数组 nums ，找出数字连续的最长序列（不要求序列元素在原数组中连续）的长度。
     * 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
     */
    public int longestConsecutive(int[] nums) {
        /*if (nums == null || nums.length == 0) return 0;
        int[] ints = Arrays.stream(nums).sorted().toArray();

        int result = 1;

        for (int i = 0; i < ints.length; i++) {
            int result1 = 1;
            while (true) {
                if (i + 1 == ints.length) {
                    if (result1 > result) {
                        result = result1;
                    }
                    break;
                }
                boolean b = ints[i + 1] - ints[i] == 1;
                if (b) {
                    result1 ++ ;
                } else {
                    if (result1 > result) {
                        result = result1;
                    }
                    break;
                }
            }

        }
        return result;*/
        HashSet<Integer> hashSet = new HashSet<>();

        for (int num : nums) {
            hashSet.add(num);
        }

        int longestStreak = 0;

        for (Integer num : hashSet) {

            if (!hashSet.contains(num - 1)) {
                int currNum = num;
                int total = 1;
                while (hashSet.contains(currNum + 1)) {
                    currNum += 1;
                    total += 1;
                }

                longestStreak = Math.max(longestStreak, total);
            }

        }
        return longestStreak;
    }
}
